#include "led.hpp"

static constexpr rt_base_t LED_DS0 = GET_PIN(F, 9);  // PIN of LED_DS0 is PF9
static constexpr rt_base_t LED_DS1 = GET_PIN(F, 10); // PIN of LED_DS1 is PF10
static constexpr const char *PWM_DEV_NAME = "pwm14"; // PWM device name of LED_DS0
static constexpr int PWM_DEV_CHANNEL = 1;            // PWM channel of LED_DS0

void LED::run(void *parameter)
{
    //// this->ledInit();

    // parameters of pwm
    constexpr rt_uint32_t period = 500000; /*ns*/
    rt_uint32_t pulse, dir;
    dir = 1;
    pulse = 0; /*ns*/
    // fine device
    this->pwm_dev = (rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
    if (this->pwm_dev == RT_NULL)
    {
        rt_kprintf("can't find %s device\n", PWM_DEV_NAME);
        return;
    }
    // set period and pulse
    rt_pwm_set(this->pwm_dev, PWM_DEV_CHANNEL, period, pulse);
    // enable device
    rt_pwm_enable(this->pwm_dev, PWM_DEV_CHANNEL);

    while (1)
    {
        rt_thread_mdelay(50);
        // adjust pulse
        pulse = dir ? pulse + 10000 : pulse - 10000;
        // switch direction
        if (pulse >= period)
            dir = 0;
        else if (pulse <= 0)
            dir = 1;

        // set period and pulse
        rt_pwm_set(this->pwm_dev, PWM_DEV_CHANNEL, period, pulse);
    }
}

void LED::ledInit()
{
    rt_pin_mode(LED_DS0, PIN_MODE_OUTPUT);
    rt_pin_mode(LED_DS1, PIN_MODE_OUTPUT);
    this->setLed(LED_DS0, LED_STATE::OFF);
    this->setLed(LED_DS1, LED_STATE::OFF);
    rt_thread_mdelay(1000);
}

void LED::setLed(rt_base_t led, LED_STATE state) const
{
    if (state == LED_STATE::ON)
        rt_pin_write(led, PIN_LOW);
    else
        rt_pin_write(led, PIN_HIGH);
}
